import './polyfill';
import dva from 'dva';

import createHistory from 'history/createHashHistory';
// user BrowserHistory
// import createHistory from 'history/createBrowserHistory';
import createLoading from 'dva-loading';
import 'moment/locale/zh-cn';
import * as bizcharts from 'bizcharts';
import './index.less';
import { getAuthority, setAuthority } from './utils/authority';
import { reloadAuthorized } from './utils/Authorized';
import * as keratinAuth from './services/session-auth';
import { routerRedux } from 'dva/router';

// 关闭bizcharts追踪
bizcharts.track(false);

// 1. Initialize
const app = dva({
    history: createHistory(),
});

// 2. Plugins
app.use(createLoading());

// 3. Register global model
app.model(require('./models/global').default);

// 4. Router
app.router(require('./router').default);

// 5. Start
app.start('#root');

// 6. Init sessionManger、unauthorized handler and logined user Authority
keratinAuth.setHost('auth');
keratinAuth.setCookieStore('id_token');
keratinAuth.setUnauthorizedErrorHandler(function() {
    // unauthorized? go back to login and clear user info and reset user authorization
    app._store.dispatch(routerRedux.replace('/'));
    app._store.dispatch({
        type: 'user/saveCurrentUser',
        payload: null,
    });
    setAuthority('');
    reloadAuthorized();
});
// 如果用户为初始权限0 即可以断定用户存在 则优先请求用户信息 获取进一步权限
const userAuthority = getAuthority();
if (userAuthority && userAuthority[0] === '0') {
    app._store.dispatch({
        type: 'user/fetchCurrent',
    });
}

export default app._store; // eslint-disable-line
